import 'dart:async';
import 'dart:ui';

class FunctionUtil {
  static const int _defaultDurationTime = 300;
  static Timer? timer;

  /// 防抖函数，例如用户边输入边搜索
  static void debounce(VoidCallback doSomething, {int durationTime = _defaultDurationTime}) {
    timer?.cancel();
    timer = Timer(Duration(milliseconds: durationTime), () {
      doSomething.call();
      timer = null;
    });
  }

  static const String _defaultThrottleId = 'DefaultThrottleId';
  static final Map<String, int> startTimeMap = <String, int>{_defaultThrottleId: 0};

  /// 节流函数，例如防止用户快速点击
  /// [throttleId] 用于区分不同的节流函数
  /// [durationTime] 间隔时间
  /// [continueClick] 在间隔时间内点击的回调
  /// [doSomething] 在间隔时间外点击的回调
  static void throttle(VoidCallback doSomething, {String throttleId = _defaultThrottleId, int durationTime = _defaultDurationTime, Function? continueClick}) {
    final int currentTime = DateTime.now().millisecondsSinceEpoch;
    if (currentTime - (startTimeMap[throttleId] ?? 0) > durationTime) {
      doSomething.call();
      startTimeMap[throttleId] = DateTime.now().millisecondsSinceEpoch;
    } else {
      continueClick?.call();
    }
  }
}
